import ReceiptReport from '@/pages/cues/topic/topic/components/ReceiptReport';
import TableTopicSubmit from '@/pages/cues/topic/topic/table/TableTopicSubmit';
import {
    selectCuesTopicManage,
    selectTopicManageTreeAssignOrganization,
    selectTopicManageTreeLinkageOrganization
} from '@/services/api/api-cues-topic';
import { parse } from '@/utils/historyUtils';
import {
    CloseCircleOutlined,
    FileTextOutlined,
    LikeOutlined,
    StopOutlined
} from '@ant-design/icons';
import { PageContainer, ProFormCascader } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import { useAccess } from '@umijs/max';
import {
    Button, Cascader,
    Descriptions,
    Divider,
    Spin,
    Tag,
    theme,
    Typography
} from 'antd';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import React, { useEffect, useRef, useState } from 'react';


const PageDetailsTopicRender: React.FC = () => {
    const access = useAccess();

    const formRef = useRef<ProFormInstance>();

    const [loading, setLoading] = useState(false);
    const [topicId, setTopicIdState] = useState('');
    /**
     * 指派单位数据
     */
    const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

    /**
     * 联动单位数据
     */
    const [treeLinkageOrganizationData, setTreeLinkageOrganizationDataState] = useState<DataNode[]>();

    /**
     * 选题计划详情
     */
    const [dataTopicDetails, setDataTopicDetailsState] = useState<CuesTopicData.TopicSelectManage>();

    /**
     * 申请记录
     */
    const { token } = theme.useToken();
    useEffect(() => {
        const { topicId } = parse(location.search) as { topicId: string };
        setTopicIdState(topicId);
        loadCuesTopicDetails(topicId)
        loadSelectTopicManageTreeLinkageOrganization(topicId)
        loadSelectTopicManageTreeAssignOrganization(topicId)
    }, [])
    /**
     * 预备Tree结构数据
     * @param data
     */
    function readyTreeData(data: AdminOrganizationData.Organization[]): any {
        const treeData = new Array();
        if (data) {
            data.forEach((val) => {
                treeData.push({
                    label: val.name,
                    value: val.id,
                    disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined, children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
                });
            });
        }
        return treeData;
    }

    /**
     * 加载 保存 推送 单位
     */
    const loadSelectTopicManageTreeAssignOrganization = async (id: string) => {
        try {
            const response = await selectTopicManageTreeAssignOrganization({ id: id });
            if (response.code === 0) {
                setTreeAssignOrganizationDataState(readyTreeData(response.data));
            }
        } catch (error) { }
    };

    /**
     * 加载 保存 联动 单位
     */
    const loadSelectTopicManageTreeLinkageOrganization = async (id: string) => {
        try {
            const response = await selectTopicManageTreeLinkageOrganization({
                id: id,
            });
            if (response.code === 0) {
                setTreeLinkageOrganizationDataState(readyTreeData(response.data));
            }
        } catch (error) { }
    };

    /**
     * 加载 选题计划详情
     * @param key
     */
    const loadCuesTopicDetails = async (id: string) => {
        setLoading(true);
        try {
            const response = await selectCuesTopicManage({ id: id });
            const { code, data } = response;
            if (code === 0) {
                setDataTopicDetailsState(data);
                document.title = data.name;
                formRef.current?.setFieldsValue({
                    deadlineTime: [data.createdTime, data.deadlineTime],
                    assignOrganizationIds: data.cascaderAssignOrganizations,
                    linkageOrganizationIds: data.cascaderLinkageOrganizations,
                });

                setLoading(false);
            }
        } catch (error) { }
    };


    /**
     * 级联组件 搜索筛选
     * @param inputValue
     * @param path
     * @returns
     */
    const filter = (inputValue: string, path: DefaultOptionType[]) =>
        path.some(
            (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
        );

    const IconText = ({ icon, text }: { icon: any; text: string }) => (
        <span style={{ color: '#1677FF' }}>
            {React.createElement(icon, { style: { marginInlineEnd: 8 } })}
            {text}
        </span>
    );

    const TitleText = ({ title, text }: { title: string; text: any }) => (
        <div style={{ color: '#1677FF' }}>
            {title}：{text}
        </div>
    );

    const drawerFormView = () => {
        let cover = '';

        let gradeName = '';
        let gradeColor = '';

        if (dataTopicDetails?.grade === 1) {
            cover = 'https://wx4.sinaimg.cn/mw2000/0033ImPzly1hj076fx0z4j60p00p00w502.jpg';
            gradeName = '重大';
            gradeColor = '#f50';
        } else if (dataTopicDetails?.grade === 2) {
            cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fx3ilj60p00p0wi502.jpg';
            gradeName = '重要';
            gradeColor = '#ffd591';
        } else if (dataTopicDetails?.grade === 3) {
            cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fwx7zj60p00p0tc802.jpg';
            gradeName = '一般';
            gradeColor = '#2db7f5';
        }

        let linkageTypeName = '';

        if (dataTopicDetails?.linkageType === 1) {
            linkageTypeName = '协助媒体';
        } else if (dataTopicDetails?.linkageType === 2) {
            linkageTypeName = '联动部门';
        } else if (dataTopicDetails?.linkageType === 3) {
            linkageTypeName = '协助媒体、单位';
        } else {
            linkageTypeName = '暂无';
        }

        let recordActions: React.JSX.Element[] | React.ReactNode[] | undefined = [];

        if (dataTopicDetails?.recordState === 1) {
            recordActions = [
                <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
                <IconText icon={StopOutlined} text="撤销" key="list-vertical-star-o" />,
                <IconText icon={LikeOutlined} text="发布" key="list-vertical-like-o" />,
                <IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />,
            ];
        } else if (dataTopicDetails?.recordState === 2) {
            recordActions = [
                <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
                <IconText icon={FileTextOutlined} text="详情" key="list-vertical-like-o" />,
            ];
        } else if (dataTopicDetails?.recordState === 3) {
            if (access.线索征集x配置x提供者) {
                recordActions = [
                    <TitleText
                        key={'title_text_count_submit_organization'}
                        title="上报线索"
                        text={dataTopicDetails?.countSubmit}
                    />,
                ];
            } else {
                recordActions = [
                    <TitleText
                        key={'title_text_count_submit_organization'}
                        title="上报单位"
                        text={dataTopicDetails?.countSubmitOrganization}
                    />,
                    <TitleText key={'title_text_count_submit'} title="上报线索" text={dataTopicDetails?.countSubmit} />,
                ];
            }
        } else {
            recordActions = [<IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />];
        }



        return (
            <PageContainer
                style={{ paddingInline: '20%' }}
                header={{
                    title: (
                        <div>
                            <Tag color={gradeColor}>{gradeName}</Tag>
                            <Tag color={dataTopicDetails?.run === 1 ? 'green' : dataTopicDetails?.run === 2 ? 'red' : 'orange'}>
                                {dataTopicDetails?.run === 1 ? '进行中' : dataTopicDetails?.run === 2 ? '已结束' : '已暂停'}
                            </Tag>
                            {dataTopicDetails?.isLinkage === 1 && <Tag color="orange">{linkageTypeName}</Tag>}
                            {dataTopicDetails?.name}
                        </div>
                    ),
                    breadcrumb: {
                        dataTopicDetails: [],
                    },
                    style: {
                        paddingBlockEnd: 0,
                    },
                    extra: (
                        <div>
                            {/* <Button size="small" type="primary" style={{ fontSize: 10 }}>
                                发起采访
                            </Button> */}
                            <Button size="small" style={{ marginLeft: 1, fontSize: 10 }} type="primary">
                                创作写稿
                            </Button>
                        </div>
                    )
                }}
            >
                <Spin spinning={!dataTopicDetails}>
                    <Descriptions size="small">
                        <Descriptions.Item label="单位">
                            {/* <Avatar size="small"></Avatar> */}
                            {dataTopicDetails?.createdOrganizationName}
                        </Descriptions.Item>
                        <Descriptions.Item label="创建人">
                            {dataTopicDetails?.createdAccountName}
                        </Descriptions.Item>
                        <Descriptions.Item label="联系方式">
                            {dataTopicDetails?.createdAccountPhone}
                        </Descriptions.Item>
                    </Descriptions>
                    <Descriptions size="small">
                        <Descriptions.Item label="创建日期">
                            <Typography.Text type="success">{dataTopicDetails?.createdTime}</Typography.Text>
                        </Descriptions.Item>
                        <Descriptions.Item label="截止日期">
                            <Typography.Text type="danger">{dataTopicDetails?.deadlineTime}</Typography.Text>
                        </Descriptions.Item>

                        {access.线索征集x配置x管理员 && (
                            <Descriptions.Item label="查阅媒体">
                                <ReceiptReport
                                    id={dataTopicDetails?.id}
                                    receipt={dataTopicDetails?.receipt}
                                    onRefurbish={() => {
                                        loadCuesTopicDetails(topicId)
                                    }}
                                />
                            </Descriptions.Item>
                        )}
                    </Descriptions>
                    {/* <ProForm
                    formRef={formRef}
                    submitter={false}
                >
                    <ProFormCascader
                        width="xl"
                        label={
                            <span
                                style={{
                                    color: 'rgba(0, 0, 0, 0.45)',
                                }}
                            >
                                邀请采访单位：
                            </span>
                        }
                        name="assignOrganizationIds"
                        placeholder="选择单位"
                        fieldProps={{
                            options: treeAssignOrganizationData,
                            showSearch: { filter },
                            multiple: true,
                            removeIcon: false,
                            allowClear: false,
                            maxTagCount: 'responsive',
                            showCheckedStrategy: Cascader.SHOW_CHILD,
                        }}
                    />
                </ProForm> */}
                    <div
                        style={{
                            marginTop: 24,
                        }}
                    >
                        <ProFormCascader
                            width="xl"
                            label="邀请采访单位："
                            name="assignOrganizationIds"
                            placeholder="选择单位"
                            fieldProps={{
                                value: dataTopicDetails?.cascaderAssignOrganizations,
                                options: treeAssignOrganizationData,
                                multiple: true,
                                removeIcon: false,
                                allowClear: false,
                                maxTagCount: 'responsive',
                                showCheckedStrategy: Cascader.SHOW_CHILD,
                            }}
                        />
                    </div>
                    <div
                        style={{
                            marginTop: 24,
                        }}
                    >
                        <span
                            style={{
                                color: 'rgba(0, 0, 0, 0.45)',
                            }}
                        >
                            选题内容：
                        </span>
                        <Typography.Paragraph>
                            <blockquote>{dataTopicDetails?.content}</blockquote>
                        </Typography.Paragraph>
                    </div>

                    {dataTopicDetails?.isLinkage === 1 && dataTopicDetails?.cascaderLinkageOrganizations && (
                        <>
                            <Divider />
                            <ProFormCascader
                                width="xl"
                                label={
                                    <span
                                        style={{
                                            color: 'rgba(0, 0, 0, 0.45)',
                                        }}
                                    >
                                        {dataTopicDetails?.linkageType === 1
                                            ? '协助媒体'
                                            : dataTopicDetails?.linkageType === 2
                                                ? '联动部门'
                                                : dataTopicDetails?.linkageType === 3
                                                    ? '协助媒体、单位'
                                                    : '协助媒体、单位'}
                                        ：
                                    </span>
                                }
                                name="linkageOrganizationIds"
                                placeholder="选择单位"
                                fieldProps={{
                                    options: treeLinkageOrganizationData,
                                    showSearch: { filter },
                                    multiple: true,
                                    removeIcon: false,
                                    allowClear: false,
                                    maxTagCount: 'responsive',
                                    showCheckedStrategy: Cascader.SHOW_CHILD,
                                }}
                            />
                            {dataTopicDetails?.linkageDescribes && (
                                <div
                                    style={{
                                        marginTop: 8,
                                        color: 'rgba(0, 0, 0, 0.45)',
                                    }}
                                >
                                    {dataTopicDetails?.linkageType === 1
                                        ? '协助媒体描述'
                                        : dataTopicDetails?.linkageType === 2
                                            ? '联动部门描述'
                                            : dataTopicDetails?.linkageType === 3
                                                ? '协助媒体、单位描述'
                                                : '协助媒体、单位描述'}
                                    ：
                                    <Typography.Paragraph>
                                        <blockquote>{dataTopicDetails?.linkageDescribes}</blockquote>
                                    </Typography.Paragraph>
                                </div>
                            )}
                        </>
                    )}
                    {(dataTopicDetails && !loading) && <TableTopicSubmit
                        mode={1} //开放页面
                        item={dataTopicDetails}
                        onRefurbish={function (): void {
                            loadCuesTopicDetails(topicId)
                        }}
                    />}
                </Spin>
            </PageContainer>
        );
    };

    return drawerFormView();
};
export default PageDetailsTopicRender;
